<template>
  <a-card>
    <!-- 查询条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" style="font-weight: bold">
        <a-row :gutter="48">
          <a-col :xxl="6" :lg="6" :sm="24">
            <a-form-item label="机关编号">
              <a-input v-model="queryParam.f_id" placeholder="请输入机关编号" />
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :lg="6" :sm="24">
            <a-form-item label="机关名称">
              <a-input v-model="queryParam.f_name" placeholder="请输入机关名称" />
            </a-form-item>
          </a-col>
          <a-col :xxl="6" :lg="6" :sm="24">
            <a-form-item label="单位类型">
              <a-select v-model="queryParam.f_type" placeholder="请选择单位类型" style="font-weight: normal" allowClear>
                <a-select-option v-for="unit in unitType" :key="unit.value" :value="unit.value">
                  {{ unit.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col a-col :md="6" :sm="24">
            <a-button type="primary" class="btn_primary_color" @click="queryList" icon="search">查询</a-button>
            <a-button icon="reload" class="m-l-8 btn_normal_color" @click="reQuery">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
      <div style="display: flex">
        <div class="headerdefBox">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>重置表格</span>
            </template>
            <img
              @click="resetting()"
              style="margin-right: 16px; margin-top: 30%"
              src="@/assets/icons/table/table_refresh.png"
              alt="重置"
            />
          </a-tooltip>

          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>设置表格</span>
            </template>
            <img
              @click="showHeaderDef($event)"
              style="margin-top: 30%"
              src="@/assets/icons/table/table_config.png"
              alt="表格设置"
            />
          </a-tooltip>
        </div>
        <div style="margin-bottom: 16px; margin-bottom: 10px; margin-left: 72%">
          <a-button type="primary" class="m-l-8 btn_primary_color" @click="addHandleData" icon="plus"
            >新增机关
          </a-button>
          <a-button type="primary" class="m-l-8 btn_primary_color" @click="exportExcel" icon="download">导出</a-button>
        </div>
      </div>
    </div>

    <!-- 自定义表头组件 -->
    <HEADERDEFINITION ref="headerDefRef" :ucolumns="ucolumns" @f_setColumns="s_setColumns" />

    <!-- 表格数据 -->
    <a-table
      :scroll="{ x: 1000, y: 550 }"
      :columns="ucolumns"
      :data-source="listData"
      :pagination="upagination"
      :loading="loading"
      rowKey="id"
      @change="tableChange"
      size="middle"
      :bordered="ubordered"
      :rowClassName="rowClassName"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
      </span>

      <div slot="typeSlot" slot-scope="type" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ typeLable(type) }}</span>
          </template>
          {{ typeLable(type) }}
        </a-tooltip>
      </div>

      <div slot="adidSlot" slot-scope="adid" class="overBox" style="width: 100%">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ adid === '100000' ? '中国' : adidLable(adid) }}</span>
          </template>
          {{ adid === '100000' ? '中国' : adidLable(adid) }}
        </a-tooltip>
      </div>

      <div slot="nameSlot" slot-scope="name" class="overBox" style="width: 100%; text-align: left">
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>{{ name }}</span>
          </template>
          {{ name }}
        </a-tooltip>
      </div>

      <span slot="operation" slot-scope="text, record">
        <template>
          <a @click="editHandleData(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm v-if="listData.length" title="确认删除当前数据？" @confirm="() => deleteHandleData(record)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>

    <a-drawer
      :title="isEdit ? '编辑法律机关' : '添加法律机关'"
      width="38%"
      :visible="visible_edit"
      :body-style="{ paddingBottom: '80px' }"
      @close="visible_edit = false"
      destroyOnClose
    >
      <LawDepartAdd ref="edit" @close="visible_edit = false" @reloadList="queryList" :departForm="departForm">
      </LawDepartAdd>
    </a-drawer>
  </a-card>
</template>
<script>
import { getLawPubunitPage, exportExcel, deleteLawPubunit } from '@/api/law/law_pubunit.js'
import { Tp_unitTypeList } from '@/enumeration/Tp_unit'
import storage from 'store'
import { APP_USER } from '@/store/mutation-types.js'
import adidJson from '@/components/k-form-design/packages/KFormDesign/config/cascadeData.js'

export default {
  data () {
    return {
      collapseKey: [], // 折叠面板key
      ucolumns: [
        {
          title: '序号',
          width: 50,
          key: 'index',
          align: 'center',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '机关编号',
          dataIndex: 'id',
          key: 'id',
          width: 305,
          align: 'center'
        },
        {
          title: '机关名称',
          dataIndex: 'name',
          key: 'name',
          width: 310,
          align: 'center',
          scopedSlots: { customRender: 'nameSlot' }
        },
        {
          title: '区域编码',
          dataIndex: 'adid',
          key: 'adid',
          width: 315,
          align: 'center',
          scopedSlots: { customRender: 'adidSlot' }
        },
        {
          title: '单位类型',
          width: 320,
          key: 'type',
          dataIndex: 'type',
          align: 'center',
          scopedSlots: { customRender: 'typeSlot' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 270,
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      queryParam: {
        f_id: '', //机关编码
        f_name: '', // 机关名称
        f_type: undefined, // 类型
        pageNumber: 1,
        pageSize: 20
      },
      listData: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      currentUser: storage.get(APP_USER), // 登录人信息
      Tp_unitTypeList: Tp_unitTypeList,
      Tp_unit: Tp_unitTypeList,
      unitType: [],
      visible_edit: false,
      isEdit: false,
      departForm: {
        id: '',
        name: '',
        adid: '',
        type: undefined,
        isAdd: true
      },
      adidJson: adidJson,
      myadidJson: {}
    }
  },
  components: {
    HEADERDEFINITION: () => import('@/views/customComponents/headerDefinition.vue'),
    LawDepartAdd: () => import('@/views/lawInfo/lawDepart/LawDepartAdd.vue')
  },
  computed: {},
  created () {
    this.queryParam.reguserid = this.currentUser.userId
    this.unitType = this.Tp_unit
    this.queryList()
    // 过滤当前的数据 只保留南昌的数据
    this.myadidJson = this.adidJson.cascadeData.city.filter(item => item.value == '360000')[0]
  },
  updated () {},
  methods: {
    // 重置表头方法
    resetting () {
      this.$refs.headerDefRef.f_resetting()
    },
    // 子组件回调函数, 重置表头
    s_setColumns (columns) {
      this.ucolumns = columns
    },
    // 显示自定义表头组件
    showHeaderDef (e) {
      this.$refs.headerDefRef.f_init(e)
    },
    // 新增页面
    addHandleData () {
      this.isEdit = false
      this.visible_edit = true
      this.departForm = {
        id: '',
        name: '',
        adid: '',
        type: undefined,
        isAdd: true
      }
      this.$nextTick(() => {
        this.$refs.edit.resetForm()
      })
    },

    editHandleData (record) {
      this.isEdit = true
      this.visible_edit = true
      this.departForm.id = record.id
      this.departForm.name = record.name
      this.departForm.adid = record.adid
      this.departForm.type = record.type
      this.departForm.isAdd = false
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      ;(this.queryParam = {
        f_id: '', //机关编码
        f_name: '', // 机关名称
        f_type: undefined, // 类型
        pageNumber: 1,
        pageSize: 20
      }),
        this.queryList()
    },

    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },

    typeLable (val) {
      for (let key in this.Tp_unit) {
        if (this.Tp_unit[key].value == val) {
          return this.Tp_unit[key].name
        }
      }
      return val
    },
    adidLable (val) {
      let result = val
      if (this.myadidJson.value == val) {
        result = this.myadidJson.label
      } else {
        if (this.myadidJson.children && this.myadidJson.children.length > 0) {
          for (let index = 0; index < this.myadidJson.children.length; index++) {
            let item = this.myadidJson.children[index]
            if (item.value == val) {
              result = item.label
              break
            }
            if (item.children && item.children.length > 0) {
              for (let innerIndex = 0; innerIndex < item.children.length; innerIndex++) {
                let child = item.children[innerIndex]
                if (child.value == val) {
                  result = child.label
                  break
                }
              }
            }
          }
        }
      }
      return result
    },

    queryList () {
      if (this.queryParam.f_id) {
        this.queryParam.f_id = this.queryParam.f_id.toString().trim()
      }
      if (this.queryParam.f_name) {
        this.queryParam.f_name = this.queryParam.f_name.toString().trim()
      }
      this.loading = true
      getLawPubunitPage(this.queryParam)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('获取数据失败')
          } else {
            this.listData = res.data.records
            this.upagination.total = res.data.total
            this.upagination.current = res.data.current
            this.upagination.pageSize = res.data.size
          }
        })
        .catch(err => {
          this.listData = []
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    deleteHandleData (record) {
      let id = record.id
      deleteLawPubunit({ id: id }).then(response => {
        if (response.code != 0) {
          notification.error({
            message: '错误',
            description: '删除当前数据失败'
          })
        } else {
          // 重新刷新数据
          this.queryList()
        }
      })
    },
    exportExcel () {
      exportExcel(this.queryParam)
        .then(response => {
          if (response.size == 0) {
            notification.error({
              message: '错误',
              description: '导出Excel失败'
            })
          } else {
            var blob = new Blob([response])
            var downloadElement = document.createElement('a')
            var href = window.URL.createObjectURL(blob) //创建下载的链接
            downloadElement.href = href
            downloadElement.download = this.$route.meta.title.slice(0, -4) + '.xls' //下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() //点击下载
            document.body.removeChild(downloadElement) //下载完成移除元素
            window.URL.revokeObjectURL(href) //释放掉blob对象
          }
        })
        .catch(function () {
          console.log(error)
        })
    },
    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/components/TableDrag/style.less';

::v-deep .ant-table-thead > tr > th {
  font-weight: 600;
}

.label-div {
  padding: 10px;
  height: 100%;
  display: inline-block;
  width: 100%;
}

.label-title {
  float: left;
  font-size: 16px;
  font-weight: bold;
}

.add-btn {
  float: right;
  margin-right: 20px;
}

.input-single {
  width: 200px;
}

.headerdefBox img {
  height: 20px;
  width: 20px;
}

.headerdefBox {
  // border: 1px solid red;
  margin: 0 10px 10px 0;
  display: flex;
  justify-content: end;
}

.formArea {
  margin-bottom: 30px;
}

.collapseArea {
  border: none;

  .ant-collapse-item {
    border-bottom: none;
  }

  /deep/ .ant-collapse-content {
    border-top: none;
  }
}

/deep/ .ant-collapse-header {
  background-color: #fff;
}

.collapseArea_header {
  .ant-form-item {
    margin-bottom: 0;
  }
}

.collapseArea_body {
  padding-top: 10px;
  padding: 0 20px 0 0px;
}

.overBox {
  width: 90%;
  overflow: hidden;
  /*超出部分隐藏*/
  white-space: nowrap;
  /*不换行*/
  text-overflow: ellipsis;
  /*超出部分文字以...显示*/
}
</style>
